package com.mtnz.njk.Service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.github.pagehelper.PageHelper;
import com.mtnz.njk.AlipayAppConfig.AlipayConfig;
import com.mtnz.njk.Mapper.*;
import com.mtnz.njk.UnionSDK.*;
import com.mtnz.njk.Util.AaliSMS;
import com.mtnz.njk.WxUtil.*;
import com.mtnz.njk.entity.*;
import com.mtnz.njk.model.*;
import com.mtnz.njk.result.PageInfo;
import com.mtnz.njk.result.ResponseMessage;
import com.mtnz.njk.result.ResponseResult;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 商品信息服务层
 * @Author: FBL
 * @CreateDate: 2019\7\9 0009 8:52
 * @Version: 1.0
 */
@Service
public class ProductService {

    @Autowired
    ProductMapper productMapper;

    @Autowired
    BannerMapper bannerMapper;

    @Autowired
    ProductImgMapper productImgMapper;

    @Autowired
    ProductRemarkMapper productRemarkMapper;

    @Autowired
    ProductActiveTypeMapper activeTypeMapper;

    @Autowired
    ResearchProductMapper researchMapper;

    @Autowired
    ProductUserMapper productUserMapper;

    @Autowired
    ApplyVipMapper applyVipMapper;

    @Autowired
    ProductPriceAuthorityMapper productPriceAuthorityMapper;

    @Autowired
    ProductDetailTypeMapper productDetailTypeMapper;

    @Autowired
    ProductActiveTypeMapper productActiveTypeMapper;

    @Autowired
    ComboProductMapper comboProductMapper;

    @Autowired
    CommentResearchMapper commentResearchMapper;

    @Autowired
    CartService cartService;

    @Autowired
    CartProductMapper cartProductMapper;

    @Autowired
    UserAddressMapper userAddressMapper;

    @Autowired
    CouponMapper couponMapper;

    @Autowired
    OrderInfoMapper orderInfoMapper;

    @Autowired
    OrderProductMapper orderProductMapper;

    @Autowired
    CartMapper cartMapper;

    @Autowired
    NjkUserMapper userMapper;

    @Autowired
    CountCommunityMapper countCommunityMapper;

    @Autowired
    OrderListMapper orderListMapper;

    @Autowired
    RechargeListMapper rechargeListMapper;

    @Autowired
    ProductActiveThresholdMapper productActiveThresholdMapper;

    @Autowired
    IntegralMapper integralMapper;

    @Autowired
    ComboMapper comboMapper;

    @Autowired
    ResearchMapper researchMappers;


    /**
     * 轮播图列表
     *
     * @return
     */
    public ResponseResult listBanner() throws Exception {
        List<BannerEntity> banners = bannerMapper.selectAll();
        return new ResponseResult(ResponseMessage.OK, banners);
    }

    /**
     * 商品列表(还可用与商品搜索名称展示)
     *
     * @return
     */
    public ResponseResult showListProduct(int pageNum, int pageSize) throws Exception {
        PageHelper.startPage(pageNum, pageSize);
        // 查询商品
        List<ProductEntity> products = productMapper.showListProduct();
        PageInfo<ProductEntity> productPageInfo = new PageInfo<>(products);
        // 查询商品详细类型
        List<ProductDetailTypeEntity> productDetailTypes = productDetailTypeMapper.selectAll();
        // 模块名字
        ArrayList<String> productDetailName = new ArrayList<>();
        for (ProductDetailTypeEntity productDetailTypeEntity : productDetailTypes) {
            productDetailName.add(productDetailTypeEntity.getDetailTypeName());
        }
        // 分页商品数据
        List<ProductEntity> Products = productPageInfo.getList();
        // 返回数据模型
        ArrayList<ProductListModel> productListModels = new ArrayList<>();
        // 循环专区名称
        for (String detailName : productDetailName) {
            ProductListModel productListModel = new ProductListModel();
            ArrayList<ProductEntity> productEntities = new ArrayList<>();
            for (ProductEntity product : Products) {
                // 详细类型名称相同
                if (product.getDetailTypeName().equals(detailName)) {
                    productEntities.add(product);
                }
            }
            productListModel.setName(detailName);
            productListModel.setProductEntities(productEntities);
            productListModels.add(productListModel);
        }
        return new ResponseResult(ResponseMessage.OK, productListModels);
    }


    /**
     * 商品搜索
     *
     * @param productName
     * @return
     */
    public ResponseResult searchProduct(String productName) throws Exception {
        List<ProductEntity> products = productMapper.searchProduct(productName);
        return new ResponseResult(ResponseMessage.OK, products);
    }

    /**
     * 商品详细信息
     *
     * @param userId
     * @param productId
     * @return
     */
    //  @Cacheable(cacheNames = "product", key = "#userId+'_'+#productId", unless = "#result == null ")
    public ProductEntity productDetail(String userId, String productId) throws Exception {
        // 商品详情轮播图
        List<ProductImgEntity> productImgs = productImgMapper.listProductSlideshow(productId);
        // 查看此商品详细信息
        ProductEntity productEntity = productMapper.selectByPrimaryKey(productId);
        productEntity.setProductImgEntities(productImgs);

        // 查询此商品供应商产地
        String productionName = productMapper.providerName(productEntity.getProvider());
        productEntity.setProductionName(productionName);
        List<ProductRemarkEntity> productRemarks = new ArrayList<>();
        if (productEntity.getCombo() == 1) {
            // 查询套餐商品
            Example comboExample = new Example(ComboEntity.class);
            comboExample.createCriteria().andEqualTo("productId", productEntity.getProductId());
            List<ComboEntity> comboEntities = comboMapper.selectByExample(comboExample);
            ComboEntity combo = new ComboEntity();
            ArrayList<ProductEntity> productEntities = new ArrayList<>();
            for (ComboEntity comboEntity : comboEntities) {
                String productIdCombo = comboEntity.getProductIdCombo();
                // 查询套餐里的商品信息
                ProductEntity productCombo = productMapper.selectByPrimaryKey(productIdCombo);
                String pId = productCombo.getProductId();
                // 商品详情轮播图
                List<ProductImgEntity> pImgs = productImgMapper.listProductSlideshow(pId);
                productCombo.setProductImgEntities(pImgs);

                // 查询此商品供应商产地
                String productionNam = productMapper.providerName(productCombo.getProvider());
                productCombo.setProductionName(productionNam);
                productEntities.add(productCombo);
            }
            combo.setProductEntities(productEntities);
            List<ProductEntity> productEntities1 = combo.getProductEntities();
            for (ProductEntity entity : productEntities1) {
                // 查询规格信息
                Example example = new Example(ProductRemarkEntity.class);
                example.createCriteria().andEqualTo("productId", entity.getProductId());
                productRemarks = productRemarkMapper.selectByExample(example);
                entity.setProductRemarkEntities(productRemarks);
            }
            productEntity.setComboEntity(combo);
        } else {
            // 查看此商品下的规格
            Example example = new Example(ProductRemarkEntity.class);
            example.createCriteria().andEqualTo("productId", productEntity.getProductId());
            productRemarks = productRemarkMapper.selectByExample(example);
        }

        // 查询用户信息
        NjkUserEntity njkUserEntity = productUserMapper.selectByPrimaryKey(userId);
        // 用户如果非vip不展示商品规格价格
        if (njkUserEntity != null) {
            // 用户不是vip
            if (njkUserEntity.getVip().equals("0")) {
                // 设置该规格商品价格为0，前端展示：点击咨询价格
                productRemarks.stream().forEach(e -> e.setPrice("0"));
            } else {
                // 如果是vip 查看是否拥有查看此商品的权限
                Example ProductPriceExample = new Example(ProductPriceAuthorityEntity.class);
                ProductPriceExample.createCriteria().andEqualTo("userId", njkUserEntity.getUserId()).andEqualTo("productId", productId);
                int count = productPriceAuthorityMapper.selectCountByExample(ProductPriceExample);
                // 没有查看此商品价格的权限
                if (count == 0) {
                    // 设置该规格商品价格为0，前端展示：点击咨询价格
                    productRemarks.stream().forEach(e -> e.setPrice("0"));
                }
            }

            for (ProductRemarkEntity productRemark : productRemarks) {
                // 如果该规格有活动，显示活动信息
                if (productRemark.getThresholdId() != null && productRemark.getThresholdId() != 0) {
                    // 查询阈值信息
                    ProductActiveThresholdEntity productActiveThreshold = productActiveThresholdMapper.selectByPrimaryKey(productRemark.getThresholdId());

                    // 根据活动类型id查询该规格的活动信息
                    ProductActiveTypeEntity activeTypeEntity = activeTypeMapper.selectByPrimaryKey(productActiveThreshold.getActiveTypeId());
                    // 该活动已过期或者未开始
                    if (new Date().after(productActiveThreshold.getEndTime()) || new Date().before(productActiveThreshold.getBeginTime())) {
                        // 设置商品规格活动信息
                        productRemark.setProductActiveThresholdEntity(null);
                        productRemark.setThresholdId(0);
                    } else {
                        // 买几送几
                        if (activeTypeEntity.getActiveTypeId() == 1) {
                            // 重新设置活动名字
                            activeTypeEntity.setActiveTypeName(productActiveThreshold.getActiveName());
                        }
                        // 送代金券
                        if (activeTypeEntity.getActiveTypeId() == 2) {
                            // 重新设置活动名字
                            activeTypeEntity.setActiveTypeName(productActiveThreshold.getActiveName());

                        }
                        // 换购，显示换购商品信息
                        if (activeTypeEntity.getActiveTypeId() == 3) {
                            // 查询换购商品参数信息
                            String tradRemarkId = productActiveThreshold.getTradRemarkId();
                            ProductRemarkEntity productTradRemarkEntity = productRemarkMapper.selectByPrimaryKey(tradRemarkId);

                            // 查询换购商品信息
                            ProductEntity product = productMapper.selectByPrimaryKey(productTradRemarkEntity.getProductId());
                            // 重新设置活动名字
                            activeTypeEntity.setActiveTypeName(productActiveThreshold.getActiveName());
                            // 将换购商品规格信息置入该商品规格中
                            // 实体类转模型
                            TradActiveModel productActiveModel = new TradActiveModel();
                            productActiveModel.setRemarkId(productTradRemarkEntity.getRemarkId());
                            productActiveModel.setRemark(productTradRemarkEntity.getRemark());
                            productActiveModel.setProductId(productTradRemarkEntity.getProductId());
                            productActiveModel.setSort(productTradRemarkEntity.getSort());
                            productActiveModel.setPrice(productTradRemarkEntity.getPrice());
                            productActiveModel.setMinNum(productTradRemarkEntity.getMinNum());
                            productActiveModel.setImg(productTradRemarkEntity.getImg());
                            productActiveModel.setProductExplain(productTradRemarkEntity.getProductExplain());
                            productActiveModel.setPostage(productTradRemarkEntity.getPostage());
                            productActiveModel.setPlantPrice(productTradRemarkEntity.getPlantPrice());
                            productActiveModel.setCardImg(productTradRemarkEntity.getCardImg());
                            productActiveModel.setInventory(productTradRemarkEntity.getInventory());
                            productActiveModel.setMaxNum(productTradRemarkEntity.getMaxNum());
                            productActiveModel.setThresholdId(productTradRemarkEntity.getThresholdId());
                            productActiveModel.setComboImg(productTradRemarkEntity.getComboImg());
                            productActiveModel.setShareBill(productTradRemarkEntity.getShareBill());
                            productActiveModel.setShareBillRemarkId(productTradRemarkEntity.getShareBillRemarkId());
                            productActiveModel.setProductName(product.getProductName());
                            productActiveModel.setCountGiveNum(productActiveThreshold.getThresholdThree());

                            // 将换购商品规格置入商品规格中
                            productRemark.setTradActiveModel(productActiveModel);
                        }

                        // 设置商品规格活动信息
                        productRemark.setProductActiveThresholdEntity(productActiveThreshold);
                    }
                }
            }
        }
        if (productEntity.getCombo() != 1) {
            // 加入商品规格
            productEntity.setProductRemarkEntities(productRemarks);
        }
        //查询已发布的帖子按时间排序（只两篇）
        List<ResearchEntity> researchEntities = productMapper.selectResearch(productId);

        // 实体类转模型
        List<ProductResearchModel> researchModels = new ArrayList<>();

        for (ResearchEntity researchEntity : researchEntities) {
            // 实体类转模型
            ProductResearchModel productResearchModel = new ProductResearchModel();
            productResearchModel.setContent(researchEntity.getContent());
            productResearchModel.setName(researchEntity.getName());
            productResearchModel.setCreateTime(researchEntity.getCreateTime());
            // 查询帖子的回复(只五条，用户图片,去重)
            List<String> replyimgs = commentResearchMapper.replyComment(researchEntity.getResearchId());
            productResearchModel.setReplyImgs(replyimgs);
            productResearchModel.setResearchId(researchEntity.getResearchId());
            productResearchModel.setSubject(researchEntity.getSubject());
            productResearchModel.setUserImg(researchEntity.getUserImg());
            researchModels.add(productResearchModel);
        }

        // 查询活动帖子
        List<ProductResearchActiveModel> productResearchActiveModels = new ArrayList<>();
        Example researchExample = new Example(ResearchEntity.class);
        researchExample.createCriteria().andEqualTo("productId", productId).andEqualTo("publish", 1).andEqualTo("activeStatus", 1);
        List<ResearchEntity> researchActive = researchMappers.selectByExample(researchExample);
        if (researchActive != null) {
            for (ResearchEntity researchEntity : researchActive) {
                ProductResearchActiveModel productResearchActiveModel = new ProductResearchActiveModel();
                productResearchActiveModel.setResearchId(researchEntity.getResearchId());
                productResearchActiveModel.setActiveImg(researchEntity.getActiveImg());
                productResearchActiveModels.add(productResearchActiveModel);
            }
        }

        // 加入商品帖子详情
        productEntity.setProductResearchModels(researchModels);
        // 加入活动帖子
        productEntity.setProductResearchActiveModels(productResearchActiveModels);
        // 查询商品帖子总数
        Integer countResearch = productMapper.countResearch(productId);
        // 加入商品帖子总数
        productEntity.setCountResearch(countResearch);
        return productEntity;
    }

    /**
     * 查询套餐商品详情
     *
     * @param userId
     * @param productId
     * @return
     */
    public List<ProductEntity> comboProductDetail(String userId, String productId) throws Exception {
        // 根据商品id查询出套餐中其他商品
        List<ComboEntity> comboEntities = comboProductMapper.comboProductDetail(productId);
        ArrayList<ProductEntity> productEntities = new ArrayList<>();
        for (ComboEntity comboEntity : comboEntities) {
            String productIdCombo = comboEntity.getProductIdCombo();
            // 调用查询单个商品详情接口
            ProductEntity productEntity = productDetail(userId, productIdCombo);
            productEntities.add(productEntity);
        }
        return productEntities;
    }

    /**
     * 用户咨询价格(申请成为vip)
     *
     * @param applyVip
     * @return
     */
    @Transactional
    public ResponseResult advisoryProductPrice(ApplyVipEntity applyVip) throws Exception {
        // 保存申请信息到申请表
        String applyId = IdUtil.simpleUUID();
        applyVip.setApplyVipId(applyId);
        String now = DateUtil.now();
        applyVip.setApplyDate(now);
        applyVip.setApplyStatus(2);
        int result = applyVipMapper.insertSelective(applyVip);
        if (result > 0) {
            return new ResponseResult(ResponseMessage.OK);
        }
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 确认订单
     *
     * @param userId
     * @return
     * @throws Exception
     */
    public ResponseResult verifyOrderInfo(String userId, String orderInfoId) throws Exception {
        // 查询用户的基本信息(地址是默认地址).
        NjkUserAddressEntity userAddressInfo;
        userAddressInfo = productMapper.userAddressInfo(userId);
        if (userAddressInfo == null) {
            // 查询用户的基本信息(地址不是默认地址)
            userAddressInfo = productMapper.userAddress(userId);
            if (userAddressInfo == null) {
                userAddressInfo = new NjkUserAddressEntity();
            }
        }
        // 实体类转模型
        OrderInfoModel orderInfoModel = new OrderInfoModel();

        // 查询用户余额
        NjkUserEntity userEntity = userMapper.selectByPrimaryKey(userId);
        userAddressInfo.setBalance(userEntity.getBalance());

        // 查询当前用户购物车信息
        ResponseResult responseResult = cartService.userCartList(userId, orderInfoId);
        CartMessageModel cartMessageModel = new CartMessageModel();
        if (responseResult.getInformation() instanceof CartMessageModel) {
            cartMessageModel = (CartMessageModel) responseResult.getInformation();
        }
        orderInfoModel.setProductMoney(cartMessageModel.getCountMoney());
        List<ProductEntity> productEntities = cartMessageModel.getProductEntities();


        // 客服电话
        String providerPhone = "";
        ArrayList<String> productIds = new ArrayList<>();
        ArrayList<ProductEntity> products = new ArrayList<>();
        for (ProductEntity productEntity : productEntities) {
            providerPhone = productEntity.getProviderPhone();
            productIds.add(productEntity.getProductId());
            for (ProductRemarkEntity remarkEntity : productEntity.getProductRemarkEntities()) {
                // 购物车商品规格是选中状态
                if (remarkEntity.getSelectFlag() == 1) {
                    products.add(productEntity);
                }
            }
        }


        // 查看购物车中的商品可用优惠券
        List<CouponEntity> couponEntities = productMapper.canUseCoupon(productIds, userId);

        if (userAddressInfo != null) {
            orderInfoModel.setUserName(userAddressInfo.getName());
            orderInfoModel.setUserPhone(userAddressInfo.getPhone());
            orderInfoModel.setUserAddress(userAddressInfo.getAddressDetail());
            orderInfoModel.setBalance(userAddressInfo.getBalance());
            orderInfoModel.setAddressId(userAddressInfo.getAddressId());
        }
        orderInfoModel.setProviderPhone(providerPhone);
        orderInfoModel.setProductEntities(products);
        orderInfoModel.setCanUseCoupon(couponEntities.size());
        orderInfoModel.setCouponEntities(couponEntities);

        for (ProductEntity product : products) {
            List<ProductRemarkEntity> productRemarkEntities = product.getProductRemarkEntities();
            if (productRemarkEntities != null && productRemarkEntities.size() > 0) {
                for (ProductRemarkEntity productRemarkEntity : productRemarkEntities) {
                    // 购物车中有商品规格有活动，没有优惠券可用
                    if (productRemarkEntity.getThresholdId() != 0) {
                        orderInfoModel.setCouponEntities(null);
                    }
                }
            }
        }
        return new ResponseResult(ResponseMessage.OK, orderInfoModel);
    }

    /**
     * 保存订单
     *
     * @param orderInfoEntity
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult saveOrderInfo(OrderInfoEntity orderInfoEntity) throws Exception {
        // 实付金额
        Double realityMoney = orderInfoEntity.getPayMoney();
        if (orderInfoEntity.getCouponId() != null && !orderInfoEntity.getCouponId().equals("0")) {
            // 查询优惠券信息
            String couponId = orderInfoEntity.getCouponId();
            CouponEntity couponEntity = couponMapper.selectByPrimaryKey(couponId);
            // 计算得出实付金额
            realityMoney = orderInfoEntity.getPayMoney() - Double.valueOf(couponEntity.getSubMoney());
            if (!realityMoney.equals(orderInfoEntity.getRealityMoney())) {
                return new ResponseResult(ResponseMessage.FAIL, "实际实付金额不统一");
            }
        }
        String addressId = orderInfoEntity.getAddressId();
        // 查询用户地址信息
        NjkUserAddressEntity njkUserAddressEntity = userAddressMapper.selectByPrimaryKey(addressId);
        String userAddress = njkUserAddressEntity.getAddressDetail();
        String userId = njkUserAddressEntity.getUserId();
        String userPhone = njkUserAddressEntity.getPhone();
        String userName = njkUserAddressEntity.getName();
        String province = njkUserAddressEntity.getProvince();
        String city = njkUserAddressEntity.getCity();
        int month = DateUtil.month(new Date());
        int year = DateUtil.year(new Date());
        String day = DateUtil.today();

        String orderNumber = "";
        String orderInfoId = "";
        // 待付款过来付款，修改订单信息
        if (orderInfoEntity.getOrderInfoId() != null && !("").equals(orderInfoEntity.getOrderInfoId())) {
            orderInfoId = orderInfoEntity.getOrderInfoId();
            orderNumber = orderInfoEntity.getOrderNumber();

            // 支付方式是线下支付
            boolean balance = false;
            switch (orderInfoEntity.getPayMethod()) {
                // 线下支付
                case "xx":
                    orderInfoEntity.setOrderStatus("1");
                    orderInfoEntity.setPayDate(DateUtil.now());
                    break;
                // 余额支付
                case "balance":
                    balance = true;
                    orderInfoEntity.setOrderStatus("1");
                    orderInfoEntity.setPayDate(DateUtil.now());
                    // 减少用户余额 查询用户信息
                    NjkUserEntity userEntity = userMapper.selectByPrimaryKey(userId);
                    userEntity.setUserId(orderInfoEntity.getUserId());
                    userEntity.setBalance(userEntity.getBalance() - orderInfoEntity.getRealityMoney());
                    userMapper.updateByPrimaryKeySelective(userEntity);
                    BalanceOrderEntity balanceOrderEntity = new BalanceOrderEntity();
                    // 全部使用余额支付，直接支付成功，增加一条余额支付订单
                    balanceOrderEntity.setOrderName("在线支付");
                    balanceOrderEntity.setUserId(userId);
                    balanceOrderEntity.setPayMethod(orderInfoEntity.getPayMethod());
                    balanceOrderEntity.setOrderNumber(orderNumber);
                    balanceOrderEntity.setOrderMoney(orderInfoEntity.getPayBalance());
                    balanceOrderEntity.setCreateTime(new Date());
                    balanceOrderEntity.setUserBalance(userEntity.getBalance() - orderInfoEntity.getPayBalance());
                    balanceOrderEntity.setOrderStatus(1);
                    balanceOrderEntity.setBalanceStatus(0);
                    rechargeListMapper.insertSelective(balanceOrderEntity);
                    break;
            }
            String payMethod = orderInfoEntity.getPayMethod();
            if (payMethod.equals("unionPay") || payMethod.equals("wx") || payMethod.equals("alipay")) {
                orderInfoEntity.setOrderStatus("0");
                orderInfoEntity.setDealStatus("0");
            }

            // 余额支付不为0，并且是拼加余额的形式，增加一条余额未支付订单
            if (orderInfoEntity.getPayBalance() != 0 && balance == false) {
                BalanceOrderEntity balanceOrderEntity = new BalanceOrderEntity();
                // 用户信息
                NjkUserEntity userEntity = userMapper.selectByPrimaryKey(userId);
                balanceOrderEntity.setOrderName("在线支付");
                balanceOrderEntity.setUserId(userId);
                balanceOrderEntity.setPayMethod(orderInfoEntity.getPayMethod());
                balanceOrderEntity.setOrderNumber(orderNumber);
                balanceOrderEntity.setOrderMoney(orderInfoEntity.getPayBalance());
                balanceOrderEntity.setCreateTime(new Date());
                balanceOrderEntity.setUserBalance(userEntity.getBalance() - orderInfoEntity.getPayBalance());
                balanceOrderEntity.setOrderStatus(0);
                balanceOrderEntity.setBalanceStatus(0);
                rechargeListMapper.insertSelective(balanceOrderEntity);
            }
            // 线下支付 余额支付
            if (orderInfoEntity.getPayMethod().equals("xx") || orderInfoEntity.getPayMethod().equals("balance")) {
                paySuccess(orderNumber);
            }
            // 修改订单信息
            orderInfoEntity.setOrderDate(DateUtil.now());
            int i = orderInfoMapper.updateByPrimaryKeySelective(orderInfoEntity);
            HashMap<String, Object> mm = new HashMap<>();
            mm.put("orderNum", orderNumber);
            mm.put("realityMoney", realityMoney);
            if (i > 0)
                return new ResponseResult(ResponseMessage.OK, mm);
            return new ResponseResult(ResponseMessage.FAIL);
        } else {
            // 购物车过来付款，新增订单
            orderInfoId = IdUtil.simpleUUID();
            Date now = new Date();
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String s = String.valueOf((int) ((Math.random() * 9 + 1) * 100));
            orderNumber = s + sdf1.format(now).substring(2); // 订单号
            String orderDate = DateUtil.now();
            orderInfoEntity.setOrderInfoId(orderInfoId);
            orderInfoEntity.setOrderNumber(orderNumber);
            orderInfoEntity.setOrderDate(orderDate);
            orderInfoEntity.setUserAddress(userAddress);
            orderInfoEntity.setUserId(userId);
            orderInfoEntity.setUserPhone(userPhone);
            orderInfoEntity.setUserName(userName);
            orderInfoEntity.setProvince(province);
            orderInfoEntity.setCity(city);
            orderInfoEntity.setMonth(month + "");
            orderInfoEntity.setYear(year + "");
            orderInfoEntity.setDay(day);

            int i = orderInfoMapper.insertSelective(orderInfoEntity);
            // 新增订单商品
            List<OrderProductEntity> productEntities = orderInfoEntity.getProductEntities();
            int result = 0;
            for (OrderProductEntity orderProduct : productEntities) {
                String orderProductId = IdUtil.simpleUUID();
                orderProduct.setOrderProductId(orderProductId);
                orderProduct.setOrderInfoId(orderInfoId);
                result += orderProductMapper.insertSelective(orderProduct);
            }
            // 支付方式是线下支付
            boolean balance = false;
            switch (orderInfoEntity.getPayMethod()) {
                // 线下支付
                case "xx":
                    orderInfoEntity.setOrderStatus("1");
                    orderInfoEntity.setPayDate(DateUtil.now());
                    break;
                // 余额支付
                case "balance":
                    balance = true;
                    orderInfoEntity.setOrderStatus("1");
                    orderInfoEntity.setPayDate(DateUtil.now());
                    // 减少用户余额 查询用户信息
                    NjkUserEntity userEntity = userMapper.selectByPrimaryKey(userId);
                    userEntity.setUserId(orderInfoEntity.getUserId());
                    userEntity.setBalance(userEntity.getBalance() - orderInfoEntity.getRealityMoney());
                    userMapper.updateByPrimaryKeySelective(userEntity);
                    BalanceOrderEntity balanceOrderEntity = new BalanceOrderEntity();
                    // 全部使用余额支付，直接支付成功，增加一条余额支付订单
                    balanceOrderEntity.setOrderName("在线支付");
                    balanceOrderEntity.setUserId(userId);
                    balanceOrderEntity.setPayMethod(orderInfoEntity.getPayMethod());
                    balanceOrderEntity.setOrderNumber(orderNumber);
                    balanceOrderEntity.setOrderMoney(orderInfoEntity.getPayBalance());
                    balanceOrderEntity.setCreateTime(new Date());
                    balanceOrderEntity.setUserBalance(userEntity.getBalance() - orderInfoEntity.getPayBalance());
                    balanceOrderEntity.setOrderStatus(1);
                    balanceOrderEntity.setBalanceStatus(0);
                    rechargeListMapper.insertSelective(balanceOrderEntity);
                    break;
            }
            String payMethod = orderInfoEntity.getPayMethod();
            if (payMethod.equals("unionPay") || payMethod.equals("wx") || payMethod.equals("alipay")) {
                orderInfoEntity.setOrderStatus("0");
                orderInfoEntity.setDealStatus("0");
            }
            // 余额支付不为0，并且是拼加余额的形式，增加一条余额未支付订单
            if (orderInfoEntity.getPayBalance() != 0 && balance == false) {
                BalanceOrderEntity balanceOrderEntity = new BalanceOrderEntity();
                // 用户信息
                NjkUserEntity userEntity = userMapper.selectByPrimaryKey(userId);
                balanceOrderEntity.setOrderName("在线支付");
                balanceOrderEntity.setUserId(userId);
                balanceOrderEntity.setPayMethod(orderInfoEntity.getPayMethod());
                balanceOrderEntity.setOrderNumber(orderNumber);
                balanceOrderEntity.setOrderMoney(orderInfoEntity.getPayBalance());
                balanceOrderEntity.setCreateTime(new Date());
                balanceOrderEntity.setUserBalance(userEntity.getBalance() - orderInfoEntity.getPayBalance());
                balanceOrderEntity.setOrderStatus(0);
                balanceOrderEntity.setBalanceStatus(0);
                rechargeListMapper.insertSelective(balanceOrderEntity);
            }
            // 线下支付 余额支付
            if (orderInfoEntity.getPayMethod().equals("xx") || orderInfoEntity.getPayMethod().equals("balance")) {
                paySuccess(orderNumber);
            }
            HashMap<String, Object> mm = new HashMap<>();
            mm.put("orderNum", orderNumber);
            mm.put("realityMoney", realityMoney);
            if (i > 0 && result > 0)
                return new ResponseResult(ResponseMessage.OK, mm);
            return new ResponseResult(ResponseMessage.FAIL);
        }
    }

    /**
     * 微信支付
     * 老项目中搬过来的，参数名，注释不规范懒得改
     *
     * @param request
     * @param response
     * @param orderNumber
     * @param realityMoney
     * @return
     */
    @Transactional
    public ResponseResult wxPay(HttpServletRequest request, HttpServletResponse response, String orderNumber, String realityMoney) throws Exception {
        String flag = "2";
        // 获取openId后调用统一支付接口https://api.mch.weixin.qq.com/pay/unifiedorder
        String currTime = TenpayUtil.getCurrTime();
        // 8位日期
        String strTime = currTime.substring(8, currTime.length());
        // 四位随机数
        String strRandom = TenpayUtil.buildRandom(4) + "";
        // 10位序列号,可以自行调整。
        String strReq = strTime + strRandom;

        // 商户号
        String mch_id = WxAppConfig.PARTNER;
        // 随机数
        String nonce_str = strReq;
        // 商品描述根据情况修改
        String body = "农极客";
        // 商户订单号
        String out_trade_no = orderNumber;
        // 总金额以分为单位，不带小数点
        String total_fee = realityMoney;
        // 订单生成的机器 IP
        String spbill_create_ip = request.getRemoteAddr();
        // 这里notify_url是 支付完成后微信发给该链接信息，可以判断会员是否支付成功，改变订单状态等。
        String notify_url = WxAppConfig.NOTIFY_URL;
        String trade_type = "APP";

        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("appid", WxAppConfig.APPID);
        packageParams.put("attach", flag);
        packageParams.put("mch_id", mch_id);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("body", body);
        packageParams.put("out_trade_no", out_trade_no);
        packageParams.put("total_fee", total_fee);
        packageParams.put("spbill_create_ip", spbill_create_ip);
        packageParams.put("notify_url", notify_url);
        packageParams.put("trade_type", trade_type);

        RequestHandler reqHandler = new RequestHandler(request, response);
        reqHandler.init(WxAppConfig.APPID, WxAppConfig.APPSECRET, WxAppConfig.PARTNERKEY);

        String sign = reqHandler.createSign(packageParams);
        String xml = "<xml>" + "<appid>" + WxAppConfig.APPID + "</appid>" + "<attach>" + flag + "</attach>" + "<mch_id>" + mch_id
                + "</mch_id>" + "<nonce_str>" + nonce_str + "</nonce_str>" + "<sign>" + sign + "</sign>" +
                // "<body>"+body+"</body>"+
                "<body><![CDATA[" + body + "]]></body>" + "<out_trade_no>" + out_trade_no + "</out_trade_no>"
                + "<total_fee>" + total_fee + "</total_fee>" + "<spbill_create_ip>" + spbill_create_ip
                + "</spbill_create_ip>" + "<notify_url>" + notify_url + "</notify_url>" + "<trade_type>" + trade_type
                + "</trade_type>" + "</xml>";
        // 统一下单微信url
        String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        String prepay_id = "";
        try {
            prepay_id = new GetWxOrderno().getPayNo(createOrderURL, xml);
            if (prepay_id.equals("")) {
                // ErrorMsg  统一支付接口获取预支付订单出错
                return new ResponseResult(ResponseMessage.FAIL);
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        SortedMap<String, String> finalPackage = new TreeMap<String, String>();
        String timestamp = Sha1Util.getTimeStamp();
        String nonceStr2 = nonce_str;
        String packages = prepay_id;
        finalPackage.put("appId", WxAppConfig.APPID);
        finalPackage.put("timeStamp", timestamp);
        finalPackage.put("nonceStr", nonceStr2);
        finalPackage.put("package", packages);
        finalPackage.put("signType", "MD5");
        String finalSign = reqHandler.createSign(finalPackage);
        finalPackage.put("sign", finalSign);
        return new ResponseResult(ResponseMessage.OK, finalPackage);
    }

    /**
     * 微信支付回调
     * 老项目中搬过来的（搬砖工程）
     *
     * @param request
     * @return
     */
    @Transactional
    public ResponseResult wxPayNotify(HttpServletRequest request) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        System.out.println(sb);
        Map<String, String> map = GetWxOrderno.doXMLParse(sb.toString());
        String resultCode = map.get("result_code");
        String orderNumber = map.get("out_trade_no");
        String xml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                + "<return_msg><![CDATA[签名失败]]></return_msg>" + "</xml>";
        // 回调显示支付成功
        if ("SUCCESS".equals(resultCode)) {
            // 回调成功之后的公共一些操作
            paySuccess(orderNumber);
            xml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>"
                    + "</xml>";
            return new ResponseResult(ResponseMessage.OK, xml);
        }
        return new ResponseResult(ResponseMessage.FAIL, xml);
    }

    /**
     * 支付宝支付
     * 老项目中搬过来的（搬砖工程）
     *
     * @param orderNumber
     * @param realityMoney
     * @return
     * @throws Exception
     */
    public ResponseResult alipay(String orderNumber, String realityMoney) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                AlipayConfig.APP_ID, AlipayConfig.PRIVATE_KEY, "json", AlipayConfig.INPUT_CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGN_TYPE);
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        // SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setSubject("农极客"); // 商品标题
        model.setOutTradeNo(orderNumber); // 商家订单编号
        model.setTimeoutExpress("30m"); // 超时关闭该订单时间
        model.setTotalAmount(realityMoney); // 订单总金额
        model.setProductCode(AlipayConfig.QUICK_MSECURITY_PAY); // 销售产品码，商家和支付宝签约的产品码，为固定值QUICK_MSECURITY_PAY
        model.setBody("1");
        request.setBizModel(model);
        // 回调地址
        request.setNotifyUrl(AlipayConfig.NOTIFY_URL); // 回调地址
        String orderStr = "";
        try {
            // 这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            // 就是orderString 可以直接给客户端请求，无需再做处理。
            orderStr = response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return new ResponseResult(ResponseMessage.OK, orderStr);
    }

    /**
     * 支付宝回调
     * 老项目中搬过来的（搬砖工程）
     *
     * @param request
     * @return
     */
    public ResponseResult alipayNotifyUrl(HttpServletRequest request) throws Exception {
        Map requestParams = request.getParameterMap();

        JSONObject json = JSONObject.fromObject(requestParams);
        String trade_status = json.get("trade_status").toString().substring(2,
                json.get("trade_status").toString().length() - 2);
        String out_trade_no = json.get("out_trade_no").toString().substring(2,
                json.get("out_trade_no").toString().length() - 2);
        String notify_id = json.get("notify_id").toString().substring(2, json.get("notify_id").toString().length() - 2);

        System.out.println("====================================================");
        System.out.println(json.toString());
        System.out.println("支付宝回调地址！");
        System.out.println("商户的订单号：" + out_trade_no); // orderNumber
        System.out.println("支付的状态：" + trade_status);
        // 用户支付成功
        if (trade_status.equals("TRADE_SUCCESS")) {
            // 回调成功之后的公共一些操作
            paySuccess(out_trade_no);
            return new ResponseResult(ResponseMessage.OK);
        }
        return new ResponseResult(ResponseMessage.FAIL);
    }

    /**
     * 银联支付
     * 参考银联官方demo
     *
     * @param realityMoney
     * @param orderNumber
     * @return
     * @throws Exception
     */
    public ResponseResult unionPay(String realityMoney, String orderNumber) throws Exception {
        Map<String, String> contentData = new HashMap<String, String>();
        /***银联全渠道系统，产品参数，除了encoding自行选择外其他不需修改***/
        contentData.put("version", DemoBase.version);            //版本号 全渠道默认值
        contentData.put("encoding", DemoBase.encoding);     //字符集编码 可以使用UTF-8,GBK两种方式
        contentData.put("signMethod", SDKConfig.getConfig().getSignMethod()); //签名方法
        contentData.put("txnType", "01");                        //交易类型 01:消费
        contentData.put("txnSubType", "01");                    //交易子类 01：消费
        contentData.put("bizType", "000201");                    //填写000201
        contentData.put("channelType", "08");                    //渠道类型 08手机

        /***商户接入参数***/
        contentData.put("merId", UnionpayConfig.MER_ID);                        //商户号码，请改成自己申请的商户号或者open上注册得来的777商户号测试
        contentData.put("accessType", "0");                        //接入类型，商户接入填0 ，不需修改（0：直连商户， 1： 收单机构 2：平台商户）
        contentData.put("orderId", orderNumber);                    //商户订单号，8-40位数字字母，不能含“-”或“_”，可以自行定制规则
        contentData.put("txnTime", DemoBase.getCurrentTime());                    //订单发送时间，取系统时间，格式为yyyyMMddHHmmss，必须取当前时间，否则会报txnTime无效
        contentData.put("accType", "01");                        //账号类型 01：银行卡02：存折03：IC卡帐号类型(卡介质)
        contentData.put("txnAmt", realityMoney);                        //交易金额 单位为分，不能带小数点
        contentData.put("currencyCode", "156");                 //境内商户固定 156 人民币

        // 请求方保留域，
        // 透传字段，查询、通知、对账文件中均会原样出现，如有需要请启用并修改自己希望透传的数据。
        // 出现部分特殊字符时可能影响解析，请按下面建议的方式填写：
        // 1. 如果能确定内容不会出现&={}[]"'等符号时，可以直接填写数据，建议的方法如下。
        //	contentData.put("reqReserved", "透传信息1|透传信息2|透传信息3");
        // 2. 内容可能出现&={}[]"'符号时：
        // 1) 如果需要对账文件里能显示，可将字符替换成全角＆＝｛｝【】“‘字符（自己写代码，此处不演示）；
        // 2) 如果对账文件没有显示要求，可做一下base64（如下）。
        //    注意控制数据长度，实际传输的数据长度不能超过1024位。
        //    查询、通知等接口解析时使用new String(Base64.decodeBase64(reqReserved), DemoBase.encoding);解base64后再对数据做后续解析。
        //	contentData.put("reqReserved", Base64.encodeBase64String("任意格式的信息都可以".toString().getBytes(DemoBase.encoding)));

        //后台通知地址（需设置为外网能访问 http https均可），支付成功后银联会自动将异步通知报文post到商户上送的该地址，【支付失败的交易银联不会发送后台通知】
        //后台通知参数详见open.unionpay.com帮助中心 下载  产品接口规范  网关支付产品接口规范 消费交易 商户通知
        //注意:1.需设置为外网能访问，否则收不到通知    2.http https均可  3.收单后台通知后需要10秒内返回http200或302状态码
        //    4.如果银联通知服务器发送通知后10秒内未收到返回状态码或者应答码非http200或302，那么银联会间隔一段时间再次发送。总共发送5次，银联后续间隔1、2、4、5 分钟后会再次通知。
        //    5.后台通知地址如果上送了带有？的参数，例如：http://abc/web?a=b&c=d 在后台通知处理程序验证签名之前需要编写逻辑将这些字段去掉再验签，否则将会验签失败
        contentData.put("backUrl", DemoBase.backUrl);

        /**对请求参数进行签名并发送http post请求，接收同步应答报文**/
        Map<String, String> reqData = AcpService.sign(contentData, DemoBase.encoding);             //报文中certId,signature的值是在signData方法中获取并自动赋值的，只要证书配置正确即可。
        String requestAppUrl = SDKConfig.getConfig().getAppRequestUrl();                                 //交易请求url从配置文件读取对应属性文件acp_sdk.properties中的 acpsdk.backTransUrl
        Map<String, String> rspData = AcpService.post(reqData, requestAppUrl, DemoBase.encoding);  //发送请求报文并接受同步应答（默认连接超时时间30秒，读取返回结果超时时间30秒）;这里调用signData之后，调用submitUrl之前不能对submitFromData中的键值对做任何修改，如果修改会导致验签不通过

        /**对应答码的处理，请根据您的业务逻辑来编写程序,以下应答码处理逻辑仅供参考------------->**/
        //应答码规范参考open.unionpay.com帮助中心 下载  产品接口规范  《平台接入接口规范-第5部分-附录》
        if (!rspData.isEmpty()) {
            if (AcpService.validate(rspData, DemoBase.encoding)) {
                LogUtil.writeLog("验证签名成功");
                String respCode = rspData.get("respCode");
                if (("00").equals(respCode)) {
                    //成功,获取tn号
                    String tn = rspData.get("tn");
                    // String reqMessage = DemoBase.genHtmlResult(reqData);
                    // String rspMessage = DemoBase.genHtmlResult(rspData);
                    // return new ResponseResult(ResponseMessage.OK, "请求报文:<br/>" + reqMessage + "<br/>" + "应答报文:</br>" + rspMessage + "");
                    return new ResponseResult(ResponseMessage.OK, tn);
                } else {
                    //其他应答码为失败请排查原因或做失败处理
                    return new ResponseResult(ResponseMessage.FAIL, "其他应答码为失败请排查原因或做失败处理");
                }
            } else {
                LogUtil.writeErrorLog("验证签名失败");
                return new ResponseResult(ResponseMessage.FAIL, "验证签名失败");
            }
        } else {
            //未返回正确的http状态
            LogUtil.writeErrorLog("未获取到返回报文或返回http状态码非200");
            return new ResponseResult(ResponseMessage.FAIL, "未获取到返回报文或返回http状态码非200");
        }
    }

    /**
     * 银联查询订单
     *
     * @param txnTime
     * @param orderNumber
     * @return
     * @throws Exception
     */
    public ResponseResult queryUnionOrder(String txnTime, String orderNumber) throws Exception {
        Map<String, String> data = new HashMap<String, String>();
        /***银联全渠道系统，产品参数，除了encoding自行选择外其他不需修改***/
        data.put("version", DemoBase.version);                 //版本号
        data.put("encoding", DemoBase.encoding);          //字符集编码 可以使用UTF-8,GBK两种方式
        data.put("signMethod", SDKConfig.getConfig().getSignMethod()); //签名方法
        data.put("txnType", "00");                             //交易类型 00-默认
        data.put("txnSubType", "00");                          //交易子类型  默认00
        data.put("bizType", "000201");                         //业务类型

        /***商户接入参数***/
        data.put("merId", UnionpayConfig.MER_ID);                               //商户号码，请改成自己申请的商户号或者open上注册得来的777商户号测试
        data.put("accessType", "0");                           //接入类型，商户接入固定填0，不需修改

        /***要调通交易以下字段必须修改***/
        data.put("orderId", orderNumber);                            //****商户订单号，每次发交易测试需修改为被查询的交易的订单号
        data.put("txnTime", txnTime);                            //****订单发送时间，每次发交易测试需修改为被查询的交易的订单发送时间

        /**请求参数设置完毕，以下对请求参数进行签名并发送http post请求，接收同步应答报文------------->**/

        Map<String, String> reqData = AcpService.sign(data, DemoBase.encoding);            //报文中certId,signature的值是在signData方法中获取并自动赋值的，只要证书配置正确即可。
        String url = SDKConfig.getConfig().getSingleQueryUrl();                                //交易请求url从配置文件读取对应属性文件acp_sdk.properties中的 acpsdk.singleQueryUrl
        Map<String, String> rspData = AcpService.post(reqData, url, DemoBase.encoding); //发送请求报文并接受同步应答（默认连接超时时间30秒，读取返回结果超时时间30秒）;这里调用signData之后，调用submitUrl之前不能对submitFromData中的键值对做任何修改，如果修改会导致验签不通过

        /**对应答码的处理，请根据您的业务逻辑来编写程序,以下应答码处理逻辑仅供参考------------->**/
        //应答码规范参考open.unionpay.com帮助中心 下载  产品接口规范  《平台接入接口规范-第5部分-附录》
        if (!rspData.isEmpty()) {
            if (AcpService.validate(rspData, DemoBase.encoding)) {
                LogUtil.writeLog("验证签名成功");
                if (("00").equals(rspData.get("respCode"))) {//如果查询交易成功
                    String origRespCode = rspData.get("origRespCode");
                    if (("00").equals(origRespCode)) {
                        //交易成功，更新商户订单状态
                        String tn = rspData.get("tn");
                        return new ResponseResult(ResponseMessage.OK, tn);
                    } else if (("03").equals(origRespCode) ||
                            ("04").equals(origRespCode) ||
                            ("05").equals(origRespCode)) {
                        //订单处理中或交易状态未明，需稍后发起交易状态查询交易 【如果最终尚未确定交易是否成功请以对账文件为准】
                        return new ResponseResult(ResponseMessage.FAIL, "订单处理中或交易状态未明，需稍后发起交易状态查询交易");
                    } else {
                        // 其他应答码为交易失败
                        return new ResponseResult(ResponseMessage.FAIL, "其他应答码为交易失败");
                    }
                } else if (("34").equals(rspData.get("respCode"))) {
                    //订单不存在，可认为交易状态未明，需要稍后发起交易状态查询，或依据对账结果为准
                    return new ResponseResult(ResponseMessage.FAIL, "订单不存在");
                } else {//查询交易本身失败，如应答码10/11检查查询报文是否正确
                    return new ResponseResult(ResponseMessage.FAIL, "查询交易本身失败");
                }
            } else {
                LogUtil.writeErrorLog("验证签名失败");
                return new ResponseResult(ResponseMessage.FAIL, "验证签名失败");
            }
        } else {
            //未返回正确的http状态
            LogUtil.writeErrorLog("未获取到返回报文或返回http状态码非200");
            return new ResponseResult(ResponseMessage.FAIL, "未获取到返回报文或返回http状态码非200");
        }
    }

    /**
     * 银联回调接口
     *
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    public ResponseResult unionBackUrl(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        LogUtil.writeLog("BackRcvResponse接收后台通知开始");
        String encoding = req.getParameter(SDKConstants.param_encoding);
        // 获取银联通知服务器发送的后台通知参数
        Map<String, String> reqParam = getAllRequestParam(req);
        LogUtil.printRequestLog(reqParam);

        //重要！验证签名前不要修改reqParam中的键值对的内容，否则会验签不过
        if (!AcpService.validate(reqParam, encoding)) {
            LogUtil.writeLog("验证签名结果[失败].");
            //验签失败，需解决验签问题
            return new ResponseResult(ResponseMessage.FAIL, "验证签名结果[失败].");
        } else {
            LogUtil.writeLog("验证签名结果[成功].");
            //【注：为了安全验签成功才应该写商户的成功处理逻辑】交易成功，更新商户订单状态
            String orderId = reqParam.get("orderId"); //获取后台通知的数据，其他字段也可用类似方式获取
            String respCode = reqParam.get("respCode");
            String txnTime = reqParam.get("txnTime");
            //判断respCode=00、A6后，对涉及资金类的交易，请再发起查询接口查询，确定交易成功后更新数据库。
            if (("00").equals(respCode) || ("A6").equals(respCode)) {
                ResponseResult responseResult = queryUnionOrder(txnTime, orderId);
                if (responseResult.getStatus() == 200) {
                    paySuccess(orderId);
                    return new ResponseResult(ResponseMessage.OK, HttpStatus.OK);
                }
            }
            paySuccess(orderId);
        }
        LogUtil.writeLog("BackRcvResponse接收后台通知结束");
        //返回给银联服务器http 200  状态码
        resp.getWriter().print("ok");
        return new ResponseResult(ResponseMessage.OK, HttpStatus.OK);
    }

    /**
     * 获取请求参数中所有的信息(银联用)
     *
     * @param request
     * @return
     */
    private Map<String, String> getAllRequestParam(final HttpServletRequest request) {
        Map<String, String> res = new HashMap<String, String>();
        Enumeration<?> temp = request.getParameterNames();
        if (null != temp) {
            while (temp.hasMoreElements()) {
                String en = (String) temp.nextElement();
                String value = request.getParameter(en);
                res.put(en, value);
                //在报文上送时，如果字段的值为空，则不上送<下面的处理为在获取所有参数数据时，判断若值为空，则删除这个字段>
                //System.out.println("ServletUtil类247行  temp数据的键=="+en+"     值==="+value);
                if (null == res.get(en) || "".equals(res.get(en))) {
                    res.remove(en);
                }
            }
        }
        return res;
    }

    /**
     * 商品分享
     *
     * @param userId
     * @param productId
     * @return
     * @throws Exception
     */
    @Transactional
    public ResponseResult productShare(String userId, String productId, String shareAddress) throws Exception {
        // 查询商品详细信息
        ProductEntity productEntity = productMapper.selectByPrimaryKey(productId);
        if (productEntity != null) {
            //更新分享商品数和时间
            Integer shareViews = productEntity.getShareViews();
            productEntity.getProductId();
            productEntity.setShareViews(shareViews + 1);
            productEntity.setShareTime(DateUtil.date());
            productMapper.updateByPrimaryKey(productEntity);
            // 插入一条分享记录
            CountCommunityEntity countCommunity = new CountCommunityEntity();
            countCommunity.setCommunityType(11);
            countCommunity.setUserId(userId);
            countCommunity.setCommunityId(productId);
            if (shareAddress != null && !"".equals(shareAddress)) {
                countCommunity.setNews(shareAddress);
            }
            countCommunity.setNum("1");
            countCommunity.setOrderNum("");
            countCommunity.setAudit(0);
            countCommunity.setCreateTime(new Date());
            countCommunityMapper.insertSelective(countCommunity);
            return new ResponseResult(ResponseMessage.OK);
        }
        //分享积分商品
        IntegralEntity integralEntity = integralMapper.selectByPrimaryKey(productId);
        if (integralEntity != null) {
            Integer shareViews = integralEntity.getShareViews();
            integralEntity.setShareViews(shareViews + 1);
            integralEntity.setShareTime(DateUtil.date());
            integralMapper.updateByPrimaryKey(integralEntity);
            // 插入一条分享记录
            CountCommunityEntity countCommunity = new CountCommunityEntity();
            countCommunity.setCommunityType(12);
            countCommunity.setUserId(userId);
            countCommunity.setCommunityId(productId);
            if (shareAddress != null && !"".equals(shareAddress)) {
                countCommunity.setNews(shareAddress);
            }
            countCommunity.setNum("1");
            countCommunity.setOrderNum("");
            countCommunity.setAudit(0);
            countCommunity.setCreateTime(new Date());
            countCommunityMapper.insertSelective(countCommunity);
            return new ResponseResult(ResponseMessage.OK);
        }
        return new ResponseResult(ResponseMessage.FAIL, "没有此商品或积分商品");
    }

    /**
     * 支付成功之后的公共一些操作
     *
     * @param orderNumber
     */
    private void paySuccess(String orderNumber) throws Exception {
        // 修改订单状态
        OrderInfoEntity orderInfoEntity = new OrderInfoEntity();
        orderInfoEntity.setOrderStatus("1");

        Example orderInfoExample = new Example(OrderInfoEntity.class);
        orderInfoExample.createCriteria().andEqualTo("orderNumber", orderNumber);

        OrderInfoEntity orderInfo = orderInfoMapper.selectOneByExample(orderInfoExample);
        // 该订单是购买商品
        if (orderInfo != null) {
            orderInfoMapper.updateByExampleSelective(orderInfoEntity, orderInfoExample);
            Example orderProductExample = new Example(OrderProductEntity.class);
            orderProductExample.createCriteria().andEqualTo("orderInfoId", orderInfo.getOrderInfoId());
            List<OrderProductEntity> orderProductEntities = orderProductMapper.selectByExample(orderProductExample);
            boolean active = false;
            String providerPhone = null;

            StringBuffer orderProductNames = new StringBuffer();
            for (OrderProductEntity orderProductEntity : orderProductEntities) {
                orderProductNames.append(orderProductEntity.getProductName() + ",");
                ProductEntity productEntity = productMapper.selectByPrimaryKey(orderProductEntity.getProductId());
                providerPhone = productEntity.getProviderPhone();
                if (!orderProductEntity.getActiveId().equals("0") && !orderInfo.getPayMethod().equals("xx")) {
                    active = true;
                }
                // 减少购买的商品规格库存
                // 送的赠品用减少库存吗
                productEntity.setRepertoryNum(Integer.valueOf(productEntity.getRepertoryNum()) - Integer.valueOf(orderProductEntity.getNumber()) + "");
                Example productExample = new Example(ProductEntity.class);
                productExample.createCriteria().andEqualTo("productId", orderProductEntity.getProductId());
                productMapper.updateByExampleSelective(productEntity, productExample);
            }

            // 用户id
            String userId = orderInfo.getUserId();
            // 不涉及活动
            if (active == false) {
                // 增加用户积分
                Double realityMoney = orderInfo.getRealityMoney();
                int integral = 0;
                if (realityMoney < 10000) {
                    integral = (int) (realityMoney * 0.02);
                } else if (realityMoney >= 10000 && realityMoney < 30000) {
                    integral = (int) (realityMoney * 0.03);
                } else if (realityMoney >= 30000) {
                    integral = (int) (realityMoney * 0.04);
                }
                NjkUserEntity userEntity = userMapper.selectByPrimaryKey(userId);
                userEntity.setIntegral(userEntity.getIntegral() + integral);
                userEntity.setTotalIntegral(userEntity.getTotalIntegral() + integral);
                userMapper.updateByPrimaryKeySelective(userEntity);

                // 增加一条增加积分记录
                CountCommunityEntity countCommunityEntity = new CountCommunityEntity();
                countCommunityEntity.setCommunityId(orderInfo.getOrderInfoId());
                countCommunityEntity.setCommunityType(4);
                countCommunityEntity.setCreateTime(new Date());
                countCommunityEntity.setNum(integral + "");
                countCommunityEntity.setNews("购买农极客产品");
                countCommunityEntity.setUserId(userId);
                countCommunityMapper.insertSelective(countCommunityEntity);
            }
            // 查询用户购物车
            Example cartExample = new Example(CartEntity.class);
            cartExample.createCriteria().andEqualTo("userId", userId);
            CartEntity cartEntity = cartMapper.selectOneByExample(cartExample);
            // 用户购物车选中商品清空
            Integer cartId = cartEntity.getCartId();
            Example cartProductExample = new Example(CartProductEntity.class);
            cartProductExample.createCriteria().andEqualTo("cartId", cartId).andEqualTo("selectFlag", "1");
            int i = cartProductMapper.deleteByExample(cartProductExample);

            Map<String, Object> datas = new HashMap<>();
            datas.put("name", orderNumber);
            // 发送用户支付订单成功短信
            AaliSMS.sendSms(orderInfo.getUserPhone(), AaliSMS.sendToUser, AaliSMS.josnofObject(datas));

            // 发送给客服支付订单成功短信
            Map<String, Object> provider = new HashMap<>();
            provider.put("consignee", orderInfo.getUserName());
            provider.put("number", orderInfo.getUserPhone());
            AaliSMS.sendSms(providerPhone, AaliSMS.sendToProvider, AaliSMS.josnofObject(datas));

            // httpClient调用app后台管理站内提醒
            /*  HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("userId",userId);
            paramMap.put("orderNumber",orderNumber);
            paramMap.put("type",3);
            HttpUtil.post("http://192.168.1.141:9997/manager/sendProvider",paramMap);*/

        } else {
            // 该订单是余额充值
            // 用户充值,修改用户余额
            Example rechargeListExample = new Example(BalanceOrderEntity.class);
            rechargeListExample.createCriteria().andEqualTo("orderNumber", orderNumber);
            BalanceOrderEntity balanceOrderEntity = rechargeListMapper.selectOneByExample(rechargeListExample);
            // 用户id
            NjkUserEntity userEntity = userMapper.selectByPrimaryKey(balanceOrderEntity.getUserId());
            userEntity.setBalance(userEntity.getBalance() + balanceOrderEntity.getOrderMoney());
            userMapper.updateByPrimaryKeySelective(userEntity);

            // 修改充值订单状态
            balanceOrderEntity.setOrderStatus(1);
            rechargeListMapper.updateByExampleSelective(balanceOrderEntity, rechargeListExample);
        }
    }

}
